package cn.mw.cmdb.template.service.impl;

import cn.mw.cmdb.entity.InstanceInfo;
import cn.mw.cmdb.exception.ZabbixResultException;
import cn.mw.cmdb.mongoMapper.MwTemplateConfigurationMapper;
import cn.mw.cmdb.mongoMapper.MwTemplateFunctionMapper;
import cn.mw.cmdb.mongoMapper.MwZabbixDetectorMapper;
import cn.mw.cmdb.param.InstanceSearchParam;
import cn.mw.cmdb.service.impl.BaseSearchService;
import cn.mw.cmdb.service.impl.CmdbServiceManage;
import cn.mw.cmdb.service.impl.InstanceServiceImpl;
import cn.mw.cmdb.template.constant.MwTemplateConfigurationConstant;
import cn.mw.cmdb.template.entity.*;
import cn.mw.cmdb.template.entity.convert.MwHostGroupConvertDto;
import cn.mw.cmdb.template.entity.convert.MwTemplateConvertOne;
import cn.mw.cmdb.template.entity.convert.MwTemplateHostConvert;
import cn.mw.cmdb.template.entity.convert.MwTemplateZabbixConvertDto;
import cn.mw.cmdb.template.entity.export.TemplateExportDto;
import cn.mw.cmdb.template.enums.*;
import cn.mw.cmdb.template.param.MacroParam;
import cn.mw.cmdb.template.param.MwTemplateConfigurationParam;
import cn.mw.cmdb.template.param.TemplateParam;
import cn.mw.cmdb.template.service.MwTemplateConfigurationService;
import cn.mw.cmdb.template.service.TemplateConfigurationExportManager;
import cn.mw.cmdb.template.service.TemplateConfigurationParamManager;
import cn.mw.cmdb.template.strategy.manager.TemplateDetailManage;
import cn.mw.cmdb.template.strategy.manager.TemplateImportExportManage;
import cn.mw.cmdb.template.utils.TemplateSortUtil;
import cn.mw.cmdb.view.ViewManager;
import cn.mw.components.mongodb.tool.CriteriaWrapper;
import cn.mw.main.api.common.ZabbixDubboService;
import cn.mw.microMonitorCommon.api.common.MwDropdownTableApiService;
import cn.mw.microMonitorCommon.api.common.MwTPServerService;
import cn.mw.microMonitorCommon.constants.ZabbixApiConstants;
import cn.mw.microMonitorCommon.constants.ZabbixMethodConstants;
import cn.mw.microMonitorCommon.entity.common.MwTPServerTable;
import cn.mw.microMonitorCommon.entity.zabbix.MWZabbixAPIResult;
import cn.mw.microMonitorCommon.util.IDModelType;
import cn.mw.microMonitorCommon.util.ListMapObjUtils;
import cn.mw.microMonitorCommon.util.ModuleIDManager;
import com.alibaba.fastjson2.JSONArray;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

import static cn.mw.cmdb.processor.MonitorValue.HostTemplateIdKey;
import static cn.mw.cmdb.processor.MonitorValue.MonitorServerIdKey;
import static cn.mw.cmdb.util.ValConvertUtil.strValueConvert;

/**
 * @description 模板配置实现
 */
@Slf4j
@Service
public class MwTemplateConfigurationServiceImpl extends BaseSearchService<MwTemplateConfigurationDto> implements MwTemplateConfigurationService {

    private ModuleIDManager moduleIDManager;

    private ZabbixDubboService zabbixDubboService;
    private MwTemplateConfigurationMapper templateConfigurationMapper;

    private TemplateConfigurationParamManager configurationParamManager;
    private MwZabbixDetectorMapper zabbixDetectorMapper;

    private TemplateDetailManage templateDetailManage;

    private ViewManager viewManager;

    private TemplateConfigurationExportManager configurationExportManager;

    private TemplateImportExportManage importExportManage;

    private MwTemplateFunctionMapper templateFunctionMapper;

    @DubboReference(check = false, timeout = 12000, mock = "true")
    public MwTPServerService tpServerService;

    @DubboReference(check = false, mock = "true", timeout = 120000)
    private MwDropdownTableApiService dropdownTableApiService;

    public CmdbServiceManage cmdbServiceManage;

    public MwTemplateConfigurationServiceImpl(MwTemplateConfigurationMapper templateConfigurationMapper, ModuleIDManager moduleIDManager, ZabbixDubboService zabbixDubboService,
                                              TemplateConfigurationParamManager configurationParamManager, TemplateDetailManage templateDetailManage, MwZabbixDetectorMapper zabbixDetectorMapper,
                                              ViewManager viewManager,TemplateConfigurationExportManager configurationExportManager,TemplateImportExportManage importExportManage,
                                              CmdbServiceManage cmdbServiceManage,MwTemplateFunctionMapper templateFunctionMapper) {
        this.moduleIDManager = moduleIDManager;
        this.zabbixDubboService = zabbixDubboService;
        this.templateConfigurationMapper = templateConfigurationMapper;
        this.configurationParamManager = configurationParamManager;
        this.templateDetailManage = templateDetailManage;
        this.zabbixDetectorMapper = zabbixDetectorMapper;
        this.viewManager = viewManager;
        this.configurationExportManager = configurationExportManager;
        this.importExportManage = importExportManage;
        this.cmdbServiceManage = cmdbServiceManage;
        this.templateFunctionMapper = templateFunctionMapper;
    }

    @Override
    public List<MwTemplateConfigurationDto> getTemplateInfoByServerId(MwTemplateConfigurationParam param) throws Exception {
        if(param.getServerId() == null){
            return null;
        }
        List<MwTemplateConfigurationDto> configurationDtos = new ArrayList<>();
        Map zabbixParam = configurationParamManager.getAllTemplateParam(param);
        //获取模板信息
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.TEMPLATE_GET, zabbixParam);
        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
        List<MwTemplateZabbixConvertDto> zabbixConvertDtos = JSONArray.parseArray(String.valueOf(zabbixAPIResult.getData()), MwTemplateZabbixConvertDto.class);
        if(StringUtils.isNotEmpty(param.getTemplateName())){
            zabbixConvertDtos = zabbixConvertDtos.stream().filter(item->item.getName().toLowerCase().contains(param.getTemplateName().toLowerCase())).collect(Collectors.toList());
        }
        //转为数据库存储参数
        for (MwTemplateZabbixConvertDto zabbixConvertDto : zabbixConvertDtos) {
            MwTemplateConfigurationDto configurationDto = new MwTemplateConfigurationDto();
            configurationDto.extractFrom(zabbixConvertDto, param.getServerId());
            configurationDto.setId(moduleIDManager.getIDStr(IDModelType.Model));
            List<String> linkTemplateIds = configurationDto.getLinkTemplateIds();
            List linkInfos = new ArrayList();
            if(CollectionUtils.isNotEmpty(linkTemplateIds)){
                List<MwTemplateZabbixConvertDto> dtos = zabbixConvertDtos.stream().filter(item -> linkTemplateIds.contains(item.getTemplateid())).collect(Collectors.toList());
                Map map = new HashMap();
                for (MwTemplateZabbixConvertDto dto : dtos) {
                    map.put(MwTemplateConfigurationConstant.TEMPLATE_ID,dto.getTemplateid());
                    map.put(MwTemplateConfigurationConstant.NAME,dto.getName());
                    linkInfos.add(map);
                }
                if(CollectionUtils.isNotEmpty(configurationDtos)){
                    List<MwTemplateConfigurationDto> dtoList = configurationDtos.stream().filter(item -> linkTemplateIds.contains(item.getTemplateId())).collect(Collectors.toList());
                    for (MwTemplateConfigurationDto dto : dtoList) {
                        map.put(MwTemplateConfigurationConstant.TEMPLATE_ID,dto.getTemplateId());
                        map.put(MwTemplateConfigurationConstant.NAME,dto.getTemplateName());
                        linkInfos.add(map);
                    }
                }
            }
            configurationDto.setLinkTemplate(linkInfos);
            configurationDtos.add(configurationDto);
        }
        queryTemplateHost(configurationDtos,param.getServerId());
        if(param.getIsSave() != null && !param.getIsSave()){
            return configurationDtos;
        }
        //数据排序
        List realData = TemplateSortUtil.templateSortList(configurationDtos, param,null);
        return realData;
    }


    private void queryTemplateHost(List<MwTemplateConfigurationDto> configurationDtos,Integer serverId) throws Exception {
        List<String> templateIds = configurationDtos.stream().map(s -> s.getTemplateId()).collect(Collectors.toList());
        InstanceServiceImpl instanceService = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        InstanceSearchParam instanceSearchParam = new InstanceSearchParam();
        Map instanceMapParam = new HashMap();
        instanceMapParam.put(MonitorServerIdKey,serverId);
        instanceMapParam.put(HostTemplateIdKey,templateIds);
        instanceSearchParam.setData(instanceMapParam);
        List<InstanceInfo> instanceInfos = instanceService.doSelectList(instanceSearchParam);
        Map<String, List<InstanceInfo>> templateInstanceMap = instanceInfos.stream().filter(s -> s.getData() != null && s.getData().get(HostTemplateIdKey) != null).collect(Collectors.groupingBy(s -> strValueConvert(s.getData().get(HostTemplateIdKey))));
        for (MwTemplateConfigurationDto configurationDto : configurationDtos) {
            List<InstanceInfo> infos = templateInstanceMap.get(configurationDto.getTemplateId());
            if(CollectionUtils.isNotEmpty(infos)){
                configurationDto.setHost(String.valueOf(infos.size()));
            }else{
                configurationDto.setHost(String.valueOf(0));
            }
        }
    }

    @Override
    public void createTemplateInfo(TemplateParam templateParam) {
        ZabbixVersionEnum zabbixVersion = getZabbixVersion(templateParam.getServerId());
        Map zabbixParam = configurationParamManager.createAndEditTemplateParam(templateParam,zabbixVersion);
        delMapNullValue(zabbixParam);
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, templateParam.getServerId(), ZabbixMethodConstants.TEMPLATE_CREATE, zabbixParam);
        //获取模板ID
        if(zabbixAPIResult == null || zabbixAPIResult.isFail() || zabbixAPIResult.code != 0){
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
        JsonNode jsonNode = (JsonNode) zabbixAPIResult.getData();
        JsonNode idNode = jsonNode.get(MwTemplateConfigurationConstant.TEMPLATE_IDS);
        List<MwTemplateConfigurationDto> configurationDtos = new ArrayList<>();
        if(idNode.isArray()){
            for (JsonNode node : idNode){
                MwTemplateConfigurationDto configurationDto = new MwTemplateConfigurationDto();
                configurationDto.setId(moduleIDManager.getIDStr(IDModelType.Model));
                configurationDto.setTemplateId(node.asText());
                configurationDto.setStatus(2);
                configurationDto.setServerId(templateParam.getServerId());
                configurationDtos.add(configurationDto);
            }
        }
        templateConfigurationMapper.insertAll(configurationDtos);
    }

    public void delMapNullValue(Map zabbixParam){
        Iterator iterator = zabbixParam.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            if(entry.getValue() == null){
                iterator.remove();
            }else if(entry.getValue() instanceof List){
                List list = (List) entry.getValue();
                if(CollectionUtils.isEmpty(list)){
                    iterator.remove();
                }
            }
        }
    }

    @Override
    public void updateTemplateInfo(TemplateParam templateParam) throws Exception {
        ZabbixVersionEnum zabbixVersion = getZabbixVersion(templateParam.getServerId());
        Map zabbixParam = configurationParamManager.createAndEditTemplateParam(templateParam, zabbixVersion);
        delMapNullValue(zabbixParam);
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, templateParam.getServerId(), ZabbixMethodConstants.TEMPLATE_UPDATE, zabbixParam);
        //获取模板ID
        if (zabbixAPIResult == null || zabbixAPIResult.isFail() || zabbixAPIResult.code != 0) {
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
//        log.info("updateTemplateInfo() ");
//        ObjectNode objectNode = (ObjectNode) zabbixAPIResult.getData();
//        JSONObject jsonNode = (JSONObject) zabbixAPIResult.getData();
//        JSONArray idNode = (JSONArray) jsonNode.get(MwTemplateConfigurationConstant.TEMPLATE_IDS);
//        List<String> templateIds = new ArrayList<>();
//        for (Object node : idNode) {
//            templateIds.add(node.toString());
//        }
//        if (CollectionUtils.isNotEmpty(templateIds)) {
//            Query query = new Query();
//            query.addCriteria(CriteriaWrapper.where(MwTemplateConfigurationDto::getTemplateId).in(templateIds));
//            query.addCriteria(CriteriaWrapper.where(MwTemplateConfigurationDto::getServerId).is(templateParam.getServerId()));
//            Update update = new Update();
//            update.set(CMDBTool.getFieldName(MwTemplateConfigurationDto::getStatus), 2);
//            //修改数据库数据状态
//            templateConfigurationMapper.updateMulti(query, update);
//        }
    }

    @Override
    public void deleteTemplateInfo(MwTemplateConfigurationParam param) throws Exception {
        List<String> hostIds = new ArrayList<>();
        if(param.getIsClean() != null && param.getIsClean()){
            //查询模板下面的主机
            Map zabbixParam = new HashMap();
            zabbixParam.put(MwTemplateConfigurationConstant.TEMPLATE_IDS, param.getTemplateIds());
            zabbixParam.put(MwTemplateConfigurationConstant.selectHosts,Arrays.asList(MwTemplateConfigurationConstant.HOST_ID,MwTemplateConfigurationConstant.NAME));
            MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.TEMPLATE_GET, zabbixParam);
            if(zabbixAPIResult != null && !zabbixAPIResult.isFail()){
                List<MwTemplateHostConvert> hostConverts = JSONArray.parseArray(String.valueOf(zabbixAPIResult.getData()), MwTemplateHostConvert.class);
                if(CollectionUtils.isNotEmpty(hostConverts)){
                    hostIds = hostConverts.stream().filter(s->s.getHostid() != null).map(s->s.getHostid()).collect(Collectors.toList());
                }
            }
        }
        if(CollectionUtils.isNotEmpty(hostIds)){
            //删除主机
            MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.HOST_DELETE, param.getServerId(), hostIds);
            if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
                throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
            }
        }
        //删除模板
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.TEMPLATE_DELETE, param.getTemplateIds());
        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
        //删除数据库数据
        Query query = new Query();
        query.addCriteria(CriteriaWrapper.where(MwTemplateConfigurationDto::getTemplateId).in(param.getTemplateIds()));
        templateConfigurationMapper.remove(query);
    }

    @Override
    public  List<MwHostGroupConvertDto> getHostGroup(MwTemplateConfigurationParam param) throws Exception {
        param.setIsSave(false);
        List<MwTemplateConfigurationDto> configurationDtos = getTemplateInfoByServerId(param);
        //获取所有分组ID
        Set<String> groupIds = configurationDtos.stream().map(s -> s.getGroup()).collect(Collectors.toSet());
        Map zabbixParam = new HashMap();
        zabbixParam.put(MwTemplateConfigurationConstant.GROUP_IDS,groupIds);
        MWZabbixAPIResult zabbixAPIResult = null;
        ZabbixVersionEnum zabbixVersion = getZabbixVersion(param.getServerId());
        switch (zabbixVersion){
            case ZABBIX_7:
                zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.TEMPLATE_GROUP_GET, new HashMap());
                break;
            default:
                zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.HOST_GROUP_GET, zabbixParam);
        }
        if(zabbixAPIResult == null && zabbixAPIResult.isFail()){
            return null;
        }
        Map<String, List<MwTemplateConfigurationDto>> listMap = configurationDtos.stream().filter(item->StringUtils.isNotEmpty(item.getGroup())).collect(Collectors.groupingBy(item -> item.getGroup()));
        List<MwHostGroupConvertDto> hostGroupConvertDtos = JSONArray.parseArray(String.valueOf(zabbixAPIResult.getData()), MwHostGroupConvertDto.class);
        for (MwHostGroupConvertDto hostGroupConvertDto : hostGroupConvertDtos) {
            if(!listMap.containsKey(hostGroupConvertDto.getGroupid())){
                hostGroupConvertDto.setTemplateCount(0);
                continue;
            }
            hostGroupConvertDto.setTemplateCount(listMap.get(hostGroupConvertDto.getGroupid()).size());
        }
        return hostGroupConvertDtos;
    }

    @Override
    public MwTemplateConvertOne getTemplateInfoById(MwTemplateConfigurationParam param) {
        Map zabbixParam = new HashMap();
        zabbixParam.put(MwTemplateConfigurationConstant.TEMPLATE_IDS, param.getTemplateId());
        zabbixParam.put(MwTemplateConfigurationConstant.OUTPUT, Arrays.asList(MwTemplateConfigurationConstant.TEMPLATE_ID,MwTemplateConfigurationConstant.NAME,MwTemplateConfigurationConstant.TEMPLATE_NAME,MwTemplateConfigurationConstant.DESCRIPTION));
        zabbixParam.put(MwTemplateConfigurationConstant.selectTemplates,Arrays.asList(MwTemplateConfigurationConstant.TEMPLATE_ID,MwTemplateConfigurationConstant.NAME,MwTemplateConfigurationConstant.TEMPLATE_NAME,MwTemplateConfigurationConstant.DESCRIPTION));
        zabbixParam.put(MwTemplateConfigurationConstant.selectParentTemplates,Arrays.asList(MwTemplateConfigurationConstant.TEMPLATE_ID,MwTemplateConfigurationConstant.NAME,MwTemplateConfigurationConstant.TEMPLATE_NAME,MwTemplateConfigurationConstant.DESCRIPTION));
        zabbixParam.put(MwTemplateConfigurationConstant.selectTags, MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(MwTemplateConfigurationConstant.selectMacros, MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(MwTemplateConfigurationConstant.selectGroups, Arrays.asList(MwTemplateConfigurationConstant.GROUP_ID,MwTemplateConfigurationConstant.NAME));
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.TEMPLATE_GET, zabbixParam);
        if(zabbixAPIResult == null && zabbixAPIResult.isFail()){
            return null;
        }
        List<MwTemplateConvertOne> convertOnes = JSONArray.parseArray(String.valueOf(zabbixAPIResult.getData()), MwTemplateConvertOne.class);
        if(CollectionUtils.isEmpty(convertOnes)){
            return null;
        }
        MwTemplateConvertOne mwTemplateConvertOne = convertOnes.get(0);
        List<String> templateIds = new ArrayList<>();
        List<MwTemplateConvertOne> templates = mwTemplateConvertOne.getTemplates();
        List<MwTemplateConvertOne> parentTemplates = mwTemplateConvertOne.getParentTemplates();
        if(CollectionUtils.isNotEmpty(templates)){
            templateIds.addAll(templates.stream().map(s->s.getTemplateid()).collect(Collectors.toList()));
        }
        if(CollectionUtils.isNotEmpty(parentTemplates)){
            templateIds.addAll(parentTemplates.stream().map(s->s.getTemplateid()).collect(Collectors.toList()));
        }
        List<MacroParam> inheritMacros = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(templateIds)){
            //查询链接模板的宏
            Map linkTemplateParam = new HashMap();
            linkTemplateParam.put(MwTemplateConfigurationConstant.TEMPLATE_IDS, templateIds);
            linkTemplateParam.put(MwTemplateConfigurationConstant.selectMacros, MwTemplateConfigurationConstant.EXTEND);
            MWZabbixAPIResult linkTemplateResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.TEMPLATE_GET, zabbixParam);
            if(linkTemplateResult == null && linkTemplateResult.isFail()){
                return null;
            }
            List<MwTemplateConvertOne> templateConvertOnes = JSONArray.parseArray(String.valueOf(linkTemplateResult.getData()), MwTemplateConvertOne.class);
            for (MwTemplateConvertOne templateConvertOne : templateConvertOnes) {
                if(CollectionUtils.isNotEmpty(templateConvertOne.getMacros())){
                    inheritMacros.addAll(templateConvertOne.getMacros());
                }
            }
        }
        mwTemplateConvertOne.setInheritMacros(inheritMacros);
        return mwTemplateConvertOne;
    }

    @Override
    public Object getTemplateDetailInfo(MwTemplateConfigurationParam param) {
        TemplateDetailEnum templateDetailEnum = TemplateDetailEnum.getTemplateDetailEnum(param.getDetailType());
        if(templateDetailEnum == null){
            return null;
        }
        Object data = templateDetailManage.getData(templateDetailEnum, param);
        return data;
    }

    @Override
    public void addTemplateDetailInfo(MwTemplateConfigurationParam param) {
        TemplateDetailEnum templateDetailEnum = TemplateDetailEnum.getTemplateDetailEnum(param.getDetailType());
        if(templateDetailEnum == null){
            return;
        }
        templateDetailManage.addData(templateDetailEnum, param);
    }

    @Override
    public void updateTemplateDetailInfo(MwTemplateConfigurationParam param) {
        TemplateDetailEnum templateDetailEnum = TemplateDetailEnum.getTemplateDetailEnum(param.getDetailType());
        if(templateDetailEnum == null){
            return;
        }
        templateDetailManage.updateData(templateDetailEnum, param);
    }

    @Override
    public void deleteTemplateDetailInfo(MwTemplateConfigurationParam param) {
        TemplateDetailEnum templateDetailEnum = TemplateDetailEnum.getTemplateDetailEnum(param.getDetailType());
        if(templateDetailEnum == null){
            return;
        }
        templateDetailManage.deleteData(templateDetailEnum, param);
    }

    @Override
    public Object selectTemplateDetailById(MwTemplateConfigurationParam param) {
        TemplateDetailEnum templateDetailEnum = TemplateDetailEnum.getTemplateDetailEnum(param.getDetailType());
        if(templateDetailEnum == null){
            return null;
        }
        Object data = templateDetailManage.selectDataById(templateDetailEnum, param);
        return data;
    }

    @Override
    public List<DropDownDto> getMonitorItemTypeInfo() {
        ZabbixMonitorTypeEnum[] values = ZabbixMonitorTypeEnum.values();
        List<DropDownDto> dtos = new ArrayList<>();
        for (ZabbixMonitorTypeEnum value : values) {
            DropDownDto dto = new DropDownDto();
            dto.setDropId(value.getType());
            dto.setDropValue(value.getName());
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public List<MwZabbixDetectorDto> getZabbixDetectorInfo(MwTemplateConfigurationParam param) throws Exception {
        Query query = new Query();
        if(StringUtils.isNotEmpty(param.getDetectorType())){
            query.addCriteria(CriteriaWrapper.where(MwZabbixDetectorDto::getType).is(param.getDetectorType()));
        }
        List<MwZabbixDetectorDto> detectorDtos = zabbixDetectorMapper.find(query);
        return detectorDtos;
    }

    @Override
    public void exportTemplateData(MwTemplateConfigurationParam param, HttpServletResponse response) throws Exception {
       if(CollectionUtils.isEmpty(param.getTemplateIds()) || StringUtils.isEmpty(param.getFileType())){return;}
        TemplateImportExportTypeEnum templateImportExportTypeEnum = TemplateImportExportTypeEnum.getTemplateInportExportTypeEnum(param.getFileType());
        switch (templateImportExportTypeEnum){
            case EXCEL:
                //查询zabbix模板数据
                Map zabbixParam = configurationParamManager.exportQueryParam(param.getTemplateIds());
                MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.TEMPLATE_GET, zabbixParam);
                if(zabbixAPIResult == null && zabbixAPIResult.isFail()){
                    throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
                }
                List<TemplateExportDto> templateExportDtos = JSONArray.parseArray(String.valueOf(zabbixAPIResult.getData()), TemplateExportDto.class);
                //进行数据导出
                configurationExportManager.exportTemplate(templateExportDtos,response);
                break;
            default:
                //调用不同的处理逻辑
                importExportManage.exportTemplate(templateImportExportTypeEnum,param,response);
        }

    }

    @Override
    public void importTemplateData(MwTemplateConfigurationParam param, MultipartFile file) throws Exception {
        TemplateImportExportTypeEnum templateImportExportTypeEnum = TemplateImportExportTypeEnum.getTemplateInportExportTypeEnum(param.getFileType());
        importExportManage.importTemplate(templateImportExportTypeEnum,param,file);
    }

    @Override
    public List<TriggerGroupDto> getTriggerGroupInfo(MwTemplateConfigurationParam param) throws Exception {
        List<TriggerGroupDto> triggerGroupDtos = new ArrayList<>();
        param.setPageNum(null);
        param.setPageSize(null);
        TemplateDetailEnum templateDetailEnum = TemplateDetailEnum.getTemplateDetailEnum(param.getDetailType());
        if(templateDetailEnum == null){
            return triggerGroupDtos;
        }
        TriggerLevelEnum[] triggerLevelEnums = TriggerLevelEnum.values();
        Object data = templateDetailManage.getData(templateDetailEnum, param);
        Map<String, List<TriggerDto>> triggerMap = new HashMap<>();
        if(data != null && data instanceof List){
            List triggerData = (List) data;
            if(CollectionUtils.isEmpty(triggerData)){
                return triggerGroupDtos;
            }
            List<TriggerDto> triggerDtos = ListMapObjUtils.castMapToBean(triggerData, TriggerDto.class);
            triggerMap = triggerDtos.stream().collect(Collectors.groupingBy(item -> item.getPriority()));
        }
        for (TriggerLevelEnum triggerLevelEnum : triggerLevelEnums) {
            String type = triggerLevelEnum.getType();
            List<TriggerDto> triggerDtos = triggerMap.get(type);
            TriggerGroupDto groupDto = new TriggerGroupDto();
            if(triggerDtos == null){
                groupDto.setLevel(triggerLevelEnum.getName());
                groupDto.setCount(0);
                triggerGroupDtos.add(groupDto);
                continue;
            }
            groupDto.setLevel(triggerLevelEnum.getName());
            groupDto.setCount(triggerDtos.size());
            triggerGroupDtos.add(groupDto);
        }
        return triggerGroupDtos;
    }

    @Override
    public List<FunctionClassifyDto> getZabbixFunctionInfo() {
        List<FunctionClassifyDto> functionClassifyDtoList = templateFunctionMapper.findAll();
        return functionClassifyDtoList;
    }

    @Override
    protected MwTemplateConfigurationDto genObject() {
        return new MwTemplateConfigurationDto();
    }

    private ZabbixVersionEnum getZabbixVersion(Integer serverId){
        MwTPServerTable tpServerTable = tpServerService.getMwTPServerByServiceId(serverId);
        String monitoringServerVersion = tpServerTable.getMonitoringServerVersion();
        ZabbixVersionEnum zabbixVersionEnum = ZabbixVersionEnum.getZabbixVersionEnum(monitoringServerVersion);
        return zabbixVersionEnum;
    }
}
